package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Goods;
import com.sk.bilibili.mapper.GoodsMapper;

/**
 * @author 邵康
 * @date 2021/12/09 23:27
 */
@Service
public class GoodsService extends ServiceImpl<GoodsMapper, Goods> {

    @Autowired
    private MinioService minioService;
    private static final String COVER_PATH = "goods/cover/%s.jpg";
    private static final Pattern COVER_PATTERN = Pattern.compile("/(goods/cover/.*jpg)");

    public R<Void> add(Goods goods) {
        goods.setCover(minioService.add(goods.getCoverFile(), COVER_PATH));
        save(goods);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        Goods temp = getById(id);
        minioService.delete(temp.getCover(), COVER_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Goods goods) {
        Goods temp = getById(goods.getId());
        String cover = minioService.update(COVER_PATH, COVER_PATTERN, temp.getCover(), goods.getCoverFile());
        goods.setCover(cover);
        updateById(goods);
        return R.success();
    }

    public R<IPage<Goods>> page(Integer page, Integer size, Boolean magic) {
        QueryWrapper<Goods> queryWrapper = QueryWrapperUtils.eq("magic", magic);
        return R.success(page(new Page<>(page, size), queryWrapper));
    }

}
